﻿using Inovout.Account.Web.Models;
using Inovout.RedictUrls;
using Inovout.Memberships.Models;
using Inovout.Memberships.Services;
using Inovout.Repositories;
using Inovout.Security;
using Inovout.Security.Services;
using Inovout.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Inovout.Account.Web.Filters;
using System.Web.Security;

namespace Inovout.Account.Web.Controllers
{
    [AllowAnonymous]
    public class FormsUserController : BaseController
    {
        public override ActionResult Index()
        {
            return View();
        }
        [ProtectedAction]
        public ActionResult FindPassword(string email, string key, string datetime, string returnUrl)
        {
            ViewBag.Email = email;
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordInfo model, string returnUrl, string email)
        {
            ViewBag.Email = email;
            ViewBag.ReturnUrl = returnUrl;

            ModelState.Remove("UserName");
            if (ModelState.IsValid)
            {
                FormsUserCredential formsUserCredential = null;
                FormsUserCredentialService formsUserCredentialService = Inovout.ComponentRegistry.Resolve<FormsUserCredentialService>();
                formsUserCredential = formsUserCredentialService.FindByEmail(email);
                formsUserCredential.Password = model.Password;
                formsUserCredentialService.Save(formsUserCredential);

                if (!User.Identity.IsAuthenticated)
                {
                    MembershipUserService membershipUserServiceService = Inovout.ComponentRegistry.Resolve<MembershipUserService>();
                    Inovout.Memberships.IMembershipUser membershipUser = membershipUserServiceService.FindBySystemUserName(formsUserCredential.SystemUser.Name);
                    FormsAuthentication.SetAuthCookie(membershipUser.Name, false);
                }

                return RedirectToAction("Message", new { messageType = MessageType.Success, message = Url.Encode("操作成功：您已重置自己的密码。<a href='" + returnUrl + "'>继续</a>") });
            }
            return View("FindPassWord", model);
        }


        public ActionResult EditPassword(string returnUrl, string email)
        {
            ViewBag.Email = email;
            FormsUserCredentialService formsUserCredentialService = Inovout.ComponentRegistry.Resolve<FormsUserCredentialService>();
            var formsUserCredential = formsUserCredentialService.FindByEmail(email);
            ViewBag.ReturnUrl = returnUrl;
            return View("FindPassWord");
        }


        public ActionResult Success()
        {
            return View();
        }

        private string GetLocalhostIp()
        {
            String strHostName = string.Empty;
            // Getting Ip address of local machine...
            // First get the host name of local machine.
            strHostName = Dns.GetHostName();
            Console.WriteLine("Local Machine's Host Name: " + strHostName);
            // Then using host name, get the IP address list..
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
            return addr[0].ToString();
        }

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time"> DateTime时间格式</param>
        /// <returns>Unix时间戳格式</returns>
        private int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp">Unix时间戳格式</param>
        /// <returns>C#格式时间</returns>
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// MD5 加密字符串
        /// </summary>
        /// <param name="rawPass">源字符串</param>
        /// <returns>加密后字符串</returns>
        private string MD5Encoding(string rawPass)
        {
            // 创建MD5类的默认实例：MD5CryptoServiceProvider
            MD5 md5 = MD5.Create();
            byte[] bs = Encoding.UTF8.GetBytes(rawPass);
            byte[] hs = md5.ComputeHash(bs);
            StringBuilder sb = new StringBuilder();
            foreach (byte b in hs)
            {
                // 以十六进制格式格式化
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }
    }
}